package com.tmt.im.manager.handler;

import com.alibaba.fastjson2.JSONObject;
import com.tmt.springboot.common.restful.ExecuteResult;
import com.tmt.springboot.common.restful.IExecuteResult;
import com.tmt.springboot.common.restful.ResultWrapper;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpStatusCode;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.List;

/**
 * @Description TODO
 * @Author wuyi
 * @Date 2024/8/19 13:31
 * @Version 1.0
 **/
@Getter
@Slf4j
@ControllerAdvice
public class ResponseResultHandler implements ResponseBodyAdvice<Object> {

    private static final List<Class<?>> SIMPLE_CLASS_LIST = List.of(Boolean.class, boolean.class,
            Integer.class, int.class,
            Long.class, long.class,
            String.class);
    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object returnObj, MethodParameter returnType, MediaType selectedContentType,
                                  Class<? extends HttpMessageConverter<?>> selectedConverterType,
                                  ServerHttpRequest request,
                                  ServerHttpResponse response) {
        if (returnObj == null) {
            return null;
        }

        //自动处理错误应答码。
        if (IExecuteResult.class.isAssignableFrom(returnObj.getClass())) {
            IExecuteResult<?> iExecuteResult = (IExecuteResult<?>) returnObj;
            if (iExecuteResult.getData() == null || SIMPLE_CLASS_LIST.contains(iExecuteResult.getData().getClass())) {
                ((ExecuteResult) iExecuteResult).setData(ResultWrapper.from(iExecuteResult).getData());
            }
            /*if (iExecuteResult.getCode() != ExecuteResult.SUCCESS_CODE) {
                try {
                    HttpStatusCode code = HttpStatusCode.valueOf(iExecuteResult.getCode());
                    response.setStatusCode(code);
                } catch (Exception ignored) {
                    response.setStatusCode(HttpStatusCode.valueOf(500));
                }
            }*/
        }
        return returnObj;
    }

}
